import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import Navbar from '../../components/Navbar/Navbar';
import './UploadPage.css';

const UploadPage = () => {
    const navigate = useNavigate();
    const [file, setFile] = useState(null);
    const [coverImage, setCoverImage] = useState(null);
    const [coverPreview, setCoverPreview] = useState(null); // 新增：封面预览
    const [title, setTitle] = useState('');
    const [description, setDescription] = useState('');
    const [tags, setTags] = useState([]);
    const [selectedTag, setSelectedTag] = useState('');
    const [category, setCategory] = useState('movies');
    const [isUploading, setIsUploading] = useState(false);
    const [uploadMessage, setUploadMessage] = useState('');
    const [isSuccess, setIsSuccess] = useState(false);

    const handleBack = () => {
        navigate(-1);
    };

    const handleFileChange = (e) => {
        const selectedFile = e.target.files[0];
        if (selectedFile && selectedFile.name.endsWith('.torrent')) {
            setFile(selectedFile);
        } else {
            alert('请选择.torrent格式的文件');
        }
    };

    const handleCoverImageChange = (e) => {
        const selectedFile = e.target.files[0];
        if (selectedFile) {
            if (selectedFile.type.startsWith('image/')) {
                setCoverImage(selectedFile);

                // 创建预览
                const reader = new FileReader();
                reader.onload = (event) => {
                    setCoverPreview(event.target.result);
                };
                reader.readAsDataURL(selectedFile);
            } else {
                alert('请选择图片文件');
            }
        }
    };

    const handleAddTag = () => {
        if (selectedTag && !tags.includes(selectedTag)) {
            setTags([...tags, selectedTag]);
            setSelectedTag('');
        }
    };

    const handleRemoveTag = (tagToRemove) => {
        setTags(tags.filter(tag => tag !== tagToRemove));
    };

    const uploadCoverImage = async (torrentId) => {

        if (!coverImage) return true;

        const formData = new FormData();
        formData.append('file', coverImage);
        formData.append('torrentId', torrentId.toString()); // 确保转换为字符串

        try {
            const response = await axios.post('/torrent/uploadCoverImage', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            });
            return response.data.result;
        } catch (error) {
            console.error('封面图片上传失败:', error);
            return false;
        }
    };
    const addToUploadCount = async (seedId) => {
        try {
            const response = await fetch('/user/addToUploadCount', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                },
                body: new URLSearchParams({
                    userId: localStorage.getItem('userId'),  // 确保是字符串，URLSearchParams会自动处理
                    torrentId: seedId  // 同上
                })
            });

            if (!response.ok) {
                const errorData = await response.json();
                console.error('更新用户数据失败:', errorData.msg);
            }
        } catch (error) {
            console.error('更新用户数据出错:', error);
        }
    };
    const handleSubmit = async (e) => {
        e.preventDefault();

        if (!file) {
            setUploadMessage('请选择种子文件');
            return;
        }
        if (!title) {
            setUploadMessage('请输入种子标题');
            return;
        }

        const formData = new FormData();
        formData.append('file', file);
        formData.append('user_id', localStorage.getItem('userId') || '1');
        formData.append('title', title);
        formData.append('description', description);
        formData.append('tags', tags.join(','));
        formData.append('category', category);

        try {
            setIsUploading(true);
            setUploadMessage('上传中...');
            setIsSuccess(false);

            // 1. 先上传种子文件
            const response = await axios.post('/seed/addSeed', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            });
             console.log(JSON.stringify(response))
            if (response.data.result) {

                const seedId = response.data.data?.id;
                const infoHash = response.data.data?.info_hash;
                // 2. 如果有封面图片，上传封面
                if (seedId && coverImage) {
                    const coverUploadSuccess = await uploadCoverImage(seedId);
                    if (!coverUploadSuccess) {
                        setUploadMessage('种子上传成功，但封面图片上传失败');
                        setIsUploading(false);
                        return;
                    }
                }

                if (infoHash) {

                    try {
                        const response_infoHash = await fetch(`/torrent/announce?info_hash=${infoHash}&user_id=${parseInt(localStorage.getItem('userId'))}`, {
                            headers: {
                                'Authorization': `Bearer ${localStorage.getItem('token')}`
                            }
                        });
                        if (response_infoHash.ok) {
                            await addToUploadCount(seedId);
                        }
                    } catch (error) {
                        console.error('获取评论列表出错:', error);
                    }
                }

                // 上传成功
                setIsSuccess(true);
                setUploadMessage(response.data.message || '种子上传成功');

                // 3秒后返回上一页
                setTimeout(() => {
                    navigate(-1);
                }, 3000);
            } else {
                setUploadMessage(response.data.msg || '上传失败');
            }
        } catch (error) {
            let errorMessage = '上传失败';
            if (error.response) {
                switch (error.response.status) {
                    case 400:
                        errorMessage = '参数错误，请检查输入';
                        break;
                    case 401:
                        errorMessage = '未授权，请登录';
                        break;
                    case 413:
                        errorMessage = '文件太大，请减小文件大小';
                        break;
                    case 500:
                        errorMessage = '服务器错误，请稍后重试';
                        break;
                    default:
                        errorMessage = `上传失败: ${error.response.data.message || '未知错误'}`;
                }
            } else if (error.request) {
                errorMessage = '网络错误，请检查连接';
            }
            setUploadMessage(errorMessage);
        } finally {
            setIsUploading(false);
        }
    };

    return (
        <div className="upload-page">
            <Navbar />
            <div className="upload-container">
                <div className="upload-grid">
                    <div className="upload-form-panel">
                        <div className="form-header">
                            <button className="back-button" onClick={handleBack}>
                                返回
                            </button>
                            <h2>上传种子</h2>
                        </div>

                        <form onSubmit={handleSubmit} className="upload-form">
                            <div className="form-group">
                                <label>选择种子文件 (.torrent)</label>
                                <input
                                    type="file"
                                    onChange={handleFileChange}
                                    accept=".torrent"
                                    required
                                />
                            </div>

                            <div className="form-group">
                                <label>上传封面图片 (可选)</label>
                                <input
                                    type="file"
                                    onChange={handleCoverImageChange}
                                    accept="image/*"
                                />
                                {coverImage && (
                                    <div className="cover-image-preview">
                                        <div className="file-selected">
                                            已选择: {coverImage.name}
                                        </div>
                                        {coverPreview && (
                                            <img
                                                src={coverPreview}
                                                alt="封面预览"
                                                className="cover-preview-image"
                                            />
                                        )}
                                    </div>
                                )}
                            </div>

                            <div className="form-group">
                                <label>种子标题</label>
                                <input
                                    type="text"
                                    value={title}
                                    onChange={(e) => setTitle(e.target.value)}
                                    placeholder="请输入种子标题"
                                    required
                                />
                            </div>

                            <div className="form-group">
                                <label>种子描述</label>
                                <textarea
                                    value={description}
                                    onChange={(e) => setDescription(e.target.value)}
                                    placeholder="请输入种子描述"
                                />
                            </div>

                            <div className="form-group">
                                <label>分类</label>
                                <select
                                    value={category}
                                    onChange={(e) => setCategory(e.target.value)}
                                >
                                    <option value="movies">电影</option>
                                    <option value="tv">电视剧</option>
                                    <option value="music">音乐</option>
                                    <option value="games">游戏</option>
                                    <option value="software">软件</option>
                                    <option value="other">其他</option>
                                </select>
                            </div>

                            <div className="form-group">
                                <label>标签 (可选)</label>
                                <div className="tags-input-container">
                                    <input
                                        type="text"
                                        value={selectedTag}
                                        onChange={(e) => setSelectedTag(e.target.value)}
                                        placeholder="输入标签并点击添加"
                                    />
                                    <button
                                        type="button"
                                        className="add-tag-button"
                                        onClick={handleAddTag}
                                    >
                                        添加
                                    </button>
                                </div>
                                <div className="tags-list">
                                    {tags.map((tag, index) => (
                                        <span key={index} className="tag">
                                            {tag}
                                            <button
                                                onClick={() => handleRemoveTag(tag)}
                                                className="remove-tag"
                                            >
                                                ×
                                            </button>
                                        </span>
                                    ))}
                                </div>
                            </div>

                            <div className="submit-button-container">
                                <button
                                    type="submit"
                                    className="submit-button"
                                    disabled={isUploading}
                                >
                                    {isUploading ? '上传中...' : '提交种子'}
                                </button>
                            </div>

                            {uploadMessage && (
                                <div className={`upload-message ${isSuccess ? 'success' : 'error'}`}>
                                    {uploadMessage}
                                </div>
                            )}
                        </form>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default UploadPage;
